package com.css.fxfzysx.modules.vabStructure.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzysx.base.response.RestResponse;
import com.css.fxfzysx.constants.FxfzConstants;
import com.css.fxfzysx.constants.YNEnum;
import com.css.fxfzysx.modules.cztDataMange.constans.RedisKeyConstants;
import com.css.fxfzysx.modules.cztDataMange.entity.HbpInfoEntity;
import com.css.fxfzysx.modules.cztDataMange.repository.BacInformationRepository;
import com.css.fxfzysx.modules.cztDataMange.utils.GenerationNumberUtil;
import com.css.fxfzysx.modules.vabStructure.dto.HaManageDto;
import com.css.fxfzysx.modules.vabStructure.param.ModelCalculationParam;
import com.css.fxfzysx.modules.vabStructure.repository.FshBuildingsRepository;
import com.css.fxfzysx.modules.vabStructure.service.FshBuildingsService;
import com.css.fxfzysx.modules.vabStructure.vo.HbpInfoVo;
import com.css.fxfzysx.modules.ysxManagement.entity.DynamicFieldsEntity;
import com.css.fxfzysx.modules.ysxManagement.entity.HaManageEntity;
import com.css.fxfzysx.modules.ysxManagement.repository.HaManageRepository;
import com.css.fxfzysx.modules.ysxManagement.repository.ZqtCiRepository;
import com.css.fxfzysx.util.*;
import com.css.fxfzysx.web.PlatformSessionContext;
import com.css.fxfzysx.zcpt.sys.entity.SUser;
import com.css.fxfzysx.zcpt.sys.service.SUserService;
import com.css.fxfzysx.zcpt.sys.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
@Slf4j
public class FshBuildingsServiceImpl implements FshBuildingsService {

    @Autowired
    private FshBuildingsRepository fshBuildingsRepository;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private BacInformationRepository bacInformationRepository;

    @Autowired
    private SUserService userService;

    @Resource
    private GenerationNumberUtil generationNumberUtil;

    @Autowired
    private HaManageRepository haManageRepository;

    @Autowired
    private ZqtCiRepository zqtCiRepository;

    @Override
    public RestResponse queryFshBuildings(HbpInfoEntity hbpInfoEntity, HttpServletRequest request) {
        try {
            int page = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int size = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            String userID = PlatformSessionContext.getUserID();
            String role = roleService.getRoleByUserId(userID);
            List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
            for (Map roleMap : roleMaps) {
                String roleCode = (String) roleMap.get("roleCode");
                if (roleCode.equals(FxfzConstants.CZT_PRI_GL_ROLE) || roleCode.equals(FxfzConstants.CZT_COUN_GL_ROLE)) {
                    hbpInfoEntity.setRole("0");
                } else {
                    hbpInfoEntity.setRole("1");
                }
            }
            return RestResponse.succeed(fshBuildingsRepository.queryFshBuildings(hbpInfoEntity, page, size));
        } catch (Exception e) {
            String errorMessage = "查看失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse modelCalculation(ModelCalculationParam param) {
        try {
            String chbpiIds = param.getChbpiIds();
            if (PlatformObjectUtils.isNotEmpty(chbpiIds)) {
                //后台计算,可多条
                for (String chbpiId : chbpiIds.split(",")) {
                    HbpInfoEntity hbp = bacInformationRepository.getHbpById(chbpiId);
                    HashMap<Integer, BigDecimal> paramMap = new HashMap<>();
                    paramMap.put(6,hbp.getTxzdcjwyj6());
                    paramMap.put(7,hbp.getTxzdcjwyj7());
                    paramMap.put(8,hbp.getTxzdcjwyj8());
                    paramMap.put(9,hbp.getTxzdcjwyj9());
                    paramMap.put(10,hbp.getTxzdcjwyj10());
                    if (PlatformObjectUtils.isNotEmpty(paramMap)) {
                        HashMap<Integer, Object> map = getValue(paramMap, hbp.getStructureType1());
                        HbpInfoVo entity = saveResult(map);
                        entity.setChbpiId(chbpiId);
                        fshBuildingsRepository.modifyCalculationStatus(entity);
                    } else {
                        return RestResponse.fail("失败,编号为【"+hbp.getNumber()+"】的【弹性最大层间位移角】参数为空!");
                    }
                }
                return RestResponse.succeed("成功!");
            } else {
                //详细页面点击计算
                HashMap<Integer, BigDecimal> paramMap = new HashMap<>();
                paramMap.put(6,param.getTxzdcjwyj6());
                paramMap.put(7,param.getTxzdcjwyj7());
                paramMap.put(8,param.getTxzdcjwyj8());
                paramMap.put(9,param.getTxzdcjwyj9());
                paramMap.put(10,param.getTxzdcjwyj10());
                HashMap<Integer, Object> value = getValue(paramMap, param.getType());
                HbpInfoVo hbpInfoVo = saveResult(value);
                return RestResponse.succeed(hbpInfoVo);
            }
        } catch (Exception e) {
            String errorMessage = "失败";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    private HbpInfoVo saveResult(HashMap<Integer, Object> map){
        StringBuilder ids = new StringBuilder();
        HbpInfoVo entity = new HbpInfoVo();
        HashMap<String, Object> value6 = (HashMap<String, Object>) map.get(6);
        entity.setForecastResults6(value6.get("value").toString());
        entity.setEmidAngle6(value6.get("as").toString());
        ids.append(value6.get("correctionCoefficient").toString()+",");
        HashMap<String, Object> value7 = (HashMap<String, Object>) map.get(7);
        entity.setForecastResults7(value7.get("value").toString());
        entity.setEmidAngle7(value7.get("as").toString());
        ids.append(value7.get("correctionCoefficient").toString()+",");
        HashMap<String, Object> value8 = (HashMap<String, Object>) map.get(8);
        entity.setForecastResults8(value8.get("value").toString());
        entity.setEmidAngle8(value8.get("as").toString());
        ids.append(value8.get("correctionCoefficient").toString()+",");
        HashMap<String, Object> value9 = (HashMap<String, Object>) map.get(9);
        entity.setForecastResults9(value9.get("value").toString());
        entity.setEmidAngle9(value9.get("as").toString());
        ids.append(value9.get("correctionCoefficient").toString()+",");
        HashMap<String, Object> value10 = (HashMap<String, Object>) map.get(10);
        entity.setForecastResults10(value10.get("value").toString());
        entity.setEmidAngle10(value10.get("as").toString());
        ids.append(value10.get("correctionCoefficient").toString()+",");
        entity.setCorrectionCoefficient(ids.toString());
        return entity;
    }


    public HashMap<Integer, Object> getValue(HashMap<Integer,BigDecimal> paramMap, String type) {
        HashMap<Integer, Object> resultMap = new HashMap<>();
        for (Map.Entry<Integer, BigDecimal> entry : paramMap.entrySet()) {
            BigDecimal txzdcjwyj = entry.getValue();
            Integer key = entry.getKey();
            BigDecimal newTxzdcjwyj = txzdcjwyj.multiply(new BigDecimal(100));
            String correctionCoefficient = "";
            HashMap<String, Object> valueMap = new HashMap<>();
            AtomicReference<String> value = new AtomicReference<>("");
            BigDecimal oldAs = new BigDecimal(0.42).multiply(newTxzdcjwyj.pow(2)).add((new BigDecimal(0.59))
                    .multiply(newTxzdcjwyj)).add(new BigDecimal(0.115)).setScale(4, BigDecimal.ROUND_HALF_UP);
            BigDecimal as = oldAs.divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_UP);

            List<DynamicFieldsEntity> dynamicFields = zqtCiRepository.getDynamicFields("高层结构层间位移角限值管理");

            List<HaManageEntity> allHaManage = haManageRepository.getAllHaManage();

            Map<String, DynamicFieldsEntity> dataMap = dynamicFields.stream().collect(
                    Collectors.toMap(DynamicFieldsEntity::getCbrsId,
                            w -> w));
            List<HaManageDto> collect = allHaManage.stream().map(h -> {
                return toHaManageDto(dataMap.get(h.getProjectId()), h);
            }).collect(Collectors.toList());

            if (type.equals("剪力墙结构") || type.equals("框架-剪力墙结构")) {
                type = "剪力墙和框-剪结构";
            }

            BigDecimal newAs = as.divide(new BigDecimal(100), 10, BigDecimal.ROUND_HALF_UP);

            for (HaManageDto it : collect) {
                if (it.getStructureType().equals(type)) {
                    if (it.getStructureValue().contains("~")) {
                        String[] split = it.getStructureValue().split("~");
                        ArrayList<BigDecimal> list = new ArrayList<>();
                        for (String s : split) {
                            String[] split1 = s.split("/");
                            list.add(BigDecimal.valueOf(Long.parseLong(split1[0])));
                            list.add(BigDecimal.valueOf(Long.parseLong(split1[1])));
                        }
                        if (newAs.compareTo(list.get(0).divide(list.get(1), 4, BigDecimal.ROUND_HALF_UP)) != -1 &&
                                newAs.compareTo(list.get(2).divide(list.get(3).subtract(BigDecimal.valueOf(1)), 4, BigDecimal.ROUND_HALF_UP)) != 1) {
                            value.set(it.getInfo());
                            correctionCoefficient = it.getChamId();
                        }
                    } else {
                        String[] split = it.getStructureValue().split("/");
                        if(it.getInfo().equals("基本完好")){
                            if (newAs.compareTo(new BigDecimal(split[0]).divide(new BigDecimal(split[1]).subtract(BigDecimal.valueOf(1)), 4, BigDecimal.ROUND_HALF_UP)) == -1) {
                                value.set(it.getInfo());
                                correctionCoefficient = it.getChamId();
                            }
                        }else if(it.getInfo().equals("毁坏")){
                            if (newAs.compareTo(new BigDecimal(split[0]).divide(new BigDecimal(split[1]), 4, BigDecimal.ROUND_HALF_UP)) == 1) {
                                value.set(it.getInfo());
                                correctionCoefficient = it.getChamId();
                            }
                        }
                    }
                }
            }
            valueMap.put("as", as);
            valueMap.put("value", value.get());
            valueMap.put("correctionCoefficient", correctionCoefficient);
            resultMap.put(key,valueMap);
        }
        return resultMap;
    }

    private HaManageDto toHaManageDto(DynamicFieldsEntity dynamicFieldsEntity, HaManageEntity haManage) {
        HaManageDto dto = new HaManageDto();
        dto.setChamId(haManage.getChamId());
        dto.setInfo(dynamicFieldsEntity.getInfo());
        dto.setStructureValue(haManage.getStructureValue());
        dto.setStructureType(haManage.getStructureType());
        return dto;
    }

    @Override
    public void importFshBuildings(String chbpiIds, HttpServletResponse response) {
        try {
            ArrayList<HbpInfoEntity> dataList = new ArrayList<>();
            for (String chbpiId : chbpiIds.split(",")) {
                HbpInfoEntity hbp = bacInformationRepository.getHbpById(chbpiId);
                if (PlatformObjectUtils.isNotEmpty(hbp.getProvince()) && PlatformObjectUtils.isNotEmpty(hbp.getCity()) && PlatformObjectUtils.isNotEmpty(hbp.getCounty())) {
                    StringBuilder region = new StringBuilder(hbp.getProvince()).append("-").append(hbp.getCity()).append("-").append(hbp.getCounty());
                    hbp.setRegion(region.toString());
                }
                if (PlatformObjectUtils.isNotEmpty(hbp.getStructureType()) && PlatformObjectUtils.isNotEmpty(hbp.getStructureType1())) {
                    StringBuilder st = new StringBuilder(hbp.getStructureType()).append("-").append(hbp.getStructureType1());
                    hbp.setSt(st.toString());
                }
                if (PlatformObjectUtils.isNotEmpty(hbp.getStructureType()) && PlatformObjectUtils.isNotEmpty(hbp.getStructureType1())) {
                    StringBuilder use = new StringBuilder(hbp.getStructureType()).append("-").append(hbp.getStructureType1());
                    hbp.setUse(use.toString());
                }
                dataList.add(hbp);
            }
            FileUtil.exportExcel(dataList, "高层建筑信息", "sheet1", HbpInfoEntity.class, "高层建筑信息.xls", response);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    @Override
    public RestResponse updateFshBuildings(HbpInfoEntity hbpInfoEntity) {
        try {
            if (PlatformObjectUtils.isNotEmpty(hbpInfoEntity.getForecastResults6())) {
                hbpInfoEntity.setCalculateOrNot("1");
            } else {
                hbpInfoEntity.setCalculateOrNot("0");
            }
            String user = userService.getSUser(PlatformSessionContext.getUserID());
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            if (PlatformObjectUtils.isNotEmpty(hbpInfoEntity.getChbpiId())) {
                //修改
                hbpInfoEntity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hbpInfoEntity.setUpdateUser(PlatformSessionContext.getUserID());
                fshBuildingsRepository.updateFshBuildings(hbpInfoEntity);
            } else {
                hbpInfoEntity.setChbpiId(UUIDGenerator.getUUID());
                hbpInfoEntity.setCreateUnit(sUser.getOrgName());
                hbpInfoEntity.setCreateUser(PlatformSessionContext.getUserID());
                hbpInfoEntity.setDataType(FxfzConstants.CZT_GCJZW_INFO);
                hbpInfoEntity.setBasicLibrary("0");
                hbpInfoEntity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                hbpInfoEntity.setDelFlag(YNEnum.N.toString());
                hbpInfoEntity.setNumber(generationNumberUtil.getCityInitials(hbpInfoEntity.getProvince()) +
                        generationNumberUtil.type(hbpInfoEntity.getStructureType(), hbpInfoEntity.getStructureType1()) +
                        generationNumberUtil.getFs(hbpInfoEntity.getFortification()) +
                        generationNumberUtil.getGenerationNumber(RedisKeyConstants.CZT_GCJZCS_KEY));
                fshBuildingsRepository.saveFshBuildings(hbpInfoEntity);
            }
            return RestResponse.succeed("成功");
        } catch (Exception e) {
            String errorMessage = "失败";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse queryFshBuildingsById(String chbpiId) {
        try {
            return RestResponse.succeed(fshBuildingsRepository.queryFshBuildingsById(chbpiId));
        } catch (Exception e) {
            String errorMessage = "失败";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    public RestResponse moveBasicLibraryById(String dataId, String operate) {
        try {
            fshBuildingsRepository.moveBasicLibraryById(dataId, operate);
            return RestResponse.succeed("成功");
        } catch (Exception e) {
            String errorMessage = "失败";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }
}
